package com.efast.dmom.mgmt.service.mes.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.efast.cafe.commponent.crud.service.ICrudV2Service;
import com.efast.cafe.commponent.query.service.impl.QueryServiceImpl;
import com.efast.cafe.framework.exception.FileUtilException;
import com.efast.cafe.portal.bean.common.EntityFieldInfoBean;
import com.efast.cafe.portal.bean.common.EntityInfoBean;
import com.efast.cafe.portal.entity.base.PortalBaseParameter;
import com.efast.cafe.portal.remote.common.EntityInfoQueryService;
import com.efast.cafe.portal.remote.common.ParameterService;
import com.efast.cafe.util.FileUtil;
import com.efast.dmom.mgmt.service.mes.ImportFromDirectService;
@Service
public class ImportFromDirectServiceImpl extends QueryServiceImpl implements ImportFromDirectService {
	
	@Autowired
	private ICrudV2Service crudService ;
	@Autowired
	private EntityInfoQueryService entityInfoQueryService;
//	@Autowired
//	private IQueryService queryService ;
	@Autowired
	private ParameterService parameterService;
//	ImportFileUrlBackUp
	
	@Override
	public void ImportDataFromDirectExcel() {
		PortalBaseParameter importFileUrlBackUp = parameterService.api_getParameter("ImportFileUrlBackUp","Global");
		PortalBaseParameter importFileUrl = parameterService.api_getParameter("ImportFileUrl","Global");
		PortalBaseParameter importFileMappingUrl = parameterService.api_getParameter("importFileMappingUrl","Global");
		File file = new File(importFileUrl.getParam_value());
		File mappingFile = new File(importFileMappingUrl.getParam_value());
//		String backUpPath = "D:\\ImportFileUrlBackUp\\" ;
//		File file = new File("D:\\importFileUrl\\");
//		File mappingFile = new File("D:\\importFileMappingUrl\\");
		
//		E:\内网文件
    	File [] dir = file.listFiles();//取得文件列表
    	File [] mappingDir = mappingFile.listFiles();//取得文件列表
    	SAXReader saxReader=new SAXReader();
    	Document document;
    	String xmlString="";
    	Map<String, Map<String, String>> mappingMap = new HashMap<>() ;
    	Map<String, String> mapping = new HashMap<>() ;
    	for (File file2 : mappingDir) {
    		try {
	    		document = saxReader.read(file2);
	    		xmlString=document.asXML();//将xml内容转化为字符串
    		} catch (Exception e) {
    		// TODO Auto-generated catch block
	    		e.printStackTrace();
	    		xmlString="";
    		}
    		//String xmlString=document.asXML();
    		mapping = xmlString2Map(xmlString,false); //node 属性为key  ,text 为value , 
    		mappingMap.put(file2.getName().split("\\.")[0], xmlString2Map(xmlString,true));//node 属性为value  ,text 为key , 
		}
    	for(File attachment : dir){
    		String fileName= attachment.getName().split("\\.")[0];
    		XSSFWorkbook book = null;
			try {
				book = new XSSFWorkbook(new FileInputStream(attachment));
				int sheetNum = book.getNumberOfSheets() ;
				for (int i = 0 ; i< sheetNum ; i++) {
					XSSFSheet sheet = book.getSheetAt(i);
					String entityName = mappingMap.get(fileName).get(sheet.getSheetName()) ;
					StringBuffer sql = new StringBuffer();
					List<Object> params = new ArrayList<>() ;
					List<Map<String, Object>> importConfig = new ArrayList<>() ;
					params.add(entityName);
					sql.append("select * from portal_query_import_config where entityKey= ? ");
					importConfig = queryMapBySql(sql,params);
					EntityInfoBean en = entityInfoQueryService.queryEntityInfo(entityName);
					Map<String, Object>  maps1 = new HashMap<>() ;
					if(en!=null){
						List<EntityFieldInfoBean> entityFieldInfoBeans = new ArrayList<>() ;
						List<EntityFieldInfoBean> attrs = en.getAttrs() ;
						attrs.addAll(en.getExtAttrs());
						for (EntityFieldInfoBean entityFieldInfoBean : attrs) {
							if(entityFieldInfoBean.getDisplay()!=null){
								JSONObject jsonObject = new JSONObject().parseObject(entityFieldInfoBean.getDisplay());
								Boolean active = jsonObject.getBoolean("active");
								if((active!=null && active) || active==null ){
									entityFieldInfoBeans.add(entityFieldInfoBean) ;
								}
								
								JSONObject jsonObject1 = jsonObject.getJSONObject("lovSource");
								if(jsonObject1!=null){
									String str = jsonObject1.getString("param_key") ;
									Map<String, Object> map = new HashMap<>() ;
									map.put("fieldName", entityFieldInfoBean.getField().getFieldName());
									map.put("paramKey1", str);
									map.put("valueType", "LOV");
									importConfig.add(map);
								}
							}else{
								entityFieldInfoBeans.add(entityFieldInfoBean) ;
							}
						}
						for (EntityFieldInfoBean entityFieldInfoBean : entityFieldInfoBeans) {
							maps1.put(mapping.get(entityFieldInfoBean.getField().getFieldName()),entityFieldInfoBean);
						}
					}
					
					crudService.crudImport(mappingMap.get(fileName).get(sheet.getSheetName()), attachment, mappingMap.get(fileName), maps1,importConfig);
				}
				FileUtil.copyFile(attachment, importFileUrlBackUp.getParam_value());
//				FileUtil.copyFile(attachment, backUpPath);
				FileUtil.deleteFile(attachment);
			} catch (FileUtilException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void ImportDataInsert(String entityName, File uploadFile,Map<String, Object> maps,Map<String, Object> valeMaps) {
		// TODO Auto-generated method stub
		try {
			XSSFWorkbook book = null;
			book = new XSSFWorkbook(new FileInputStream(uploadFile));
			XSSFSheet sheet = book.getSheetAt(0);
			List<Map<String, Object>> mapsList = new ArrayList<>() ;
			XSSFRow rowHeader = sheet.getRow(0);
			for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum
				// 获取最后一行的行标
				XSSFRow row = sheet.getRow(j);
				if (row != null) {
					Map<String, Object> map = new HashMap<>() ;
					for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum
						// 是获取最后一个不为空的列是第几个
						if (row.getCell(k) != null) { // getCell 获取单元格数据
							System.out.print(row.getCell(k) + "\t");
						} else {
							System.out.print("\t");
						}
						//通用校验数据格式及验证 
						map.put((String)maps.get(rowHeader.getCell(k)), row.getCell(k));
					}
					mapsList.add(map) ;
				}
				System.out.println("");
			}
			for (Map<String, Object> map : mapsList) {
				crudService.crudInsert(entityName, map, null);
			}
		} catch (Exception e) {
			// TODO: handle exception
			throw new ServiceException("read.data.from.excel.failed");
		}
	}

	
	/**  
     * 循环解析xml  
     * @param ele  
     * @param map  
     * @return  
     */  
    @SuppressWarnings({ "unchecked" })  
    private static Map<String, String> recGetXmlElementValue(Element ele, Map<String, String> map,boolean flag){  
        List<Element> eleList = ele.elements();  
        if (eleList.size() == 0) {  
        	if(flag){
        		map.put(ele.getTextTrim(), ele.getName());  
        	}else{
        		map.put( ele.getName(),ele.getTextTrim());  
        	}
            return map;  
        } else {  
            for (Iterator<Element> iter = eleList.iterator(); iter.hasNext();) {  
                Element innerEle = iter.next();  
                recGetXmlElementValue(innerEle, map,flag);  
            }  
            return map;  
        }  
    }  
    
    /**  
     * Xml string转换成Map  
     * @param xmlStr  
     * @return  
     */  
    public static Map<String,String> xmlString2Map(String xmlStr,boolean flag){  
        Map<String,String> map = new HashMap<String,String>();  
        Document doc;  
        try {  
            doc = DocumentHelper.parseText(xmlStr);  
            Element el = doc.getRootElement();  
            map = recGetXmlElementValue(el,map,flag);  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        }  
        return map;  
    }  
}
